/**
 * 
 */
package co.com.ebusiness.trader.pages;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.BeanEditForm;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Session;

import co.com.ebusiness.trader.core.model.Empresa;
import co.com.ebusiness.trader.seguridad.model.Usuario;
import co.com.ebusiness.trader.seguridad.model.UsuarioEmpresa;
import co.com.ebusiness.trader.services.TraderService;

/**
 * @author Luis Agudelo
 *
 */
public class CrearVenta {
	
	// Screen fields
	
		@Property
		private co.com.ebusiness.trader.model.Venta venta;

		// Other pages
		
		@InjectPage
		private VentaDiaria indexPage;
		
		// Generally useful bits and pieces
		
		@SuppressWarnings("unused")
		@Component(id = "ventaForm")
		private BeanEditForm ventaForm;

		@Inject
		private TraderService traderService;
		
		@Inject
	 	private Request request;		
		
		void onPrepare() throws Exception {
			venta = new co.com.ebusiness.trader.model.Venta();
		}
		
		
		
		@CommitAfter
		void onValidateFromVentaForm() {
			try {
				Session session = request.getSession(false);
				Empresa empresa = null;
				Usuario usuario = null;
				if (session != null && session.getAttribute("state:Index::empresa") != null){
					empresa = ((UsuarioEmpresa)session.getAttribute("state:Index::empresa")).getEmpresa();
					usuario = ((UsuarioEmpresa)session.getAttribute("state:Index::empresa")).getUsuario();
		 		}
				venta.setEmpresa(empresa);
				venta.setUsuario(usuario);
				traderService.guardarVenta(venta);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}

		Object onSuccess() {
			return indexPage;
		}

}
